package
{
	import com.fa.map.Map;
	import com.fa.model.Food;
	import com.fa.model.Snake;
	import com.fa.model.SnakeSegment;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;

	[SWF(width = "500", height = "500", frameRate = "10", backgroundColor = '0x282828')]
	
	public class SnakeGame extends Sprite  {
		private static const FOOD_COUNT:int = 10;
		
		private var map:Map;
		private var snake:Snake;
		private var foods:Array = new Array();
		
		public function SnakeGame(){
			initMap();
			initFood();
			initSnake();

			addEventListener(Event.ENTER_FRAME, enterFrameListener);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);
			
			
			test({"a":10, "b":50});
			
		}
		
		
		private function initMap():void{
			map = new Map();
			addChild(map);
		}
		
		private function initSnake():void{
			snake = new Snake();
			addChild(snake);
		}
		
		private function initFood():void{
			for(var i:int = 0; i < FOOD_COUNT; i++){
				var row:int = Math.random() * Map.ROW;
				var col:int = Math.random() * Map.COL;
				var food:Food = new Food(row, col);
				foods.push(food);
				addChild(food);
			}
		}
		
		private function enterFrameListener (e:Event):void{
			snake.move();
			for(var i:int = 0; i < FOOD_COUNT; i++){
				if(!Food(foods[i]).hasEaten()){
					if(snake.eat(foods[i])){
						foods[i].beEaten();
						removeChild(foods[i]);
					}
				}
			}
		}
		
		private function keyDownListener (e:KeyboardEvent):void{
			var code:uint=e.keyCode

			if(code == Keyboard.UP){
				snake.turn(SnakeSegment.UP);
			} else if (code == Keyboard.LEFT) {
				snake.turn(SnakeSegment.LEFT);
			} else if (code == Keyboard.DOWN) {
				snake.turn(SnakeSegment.DOWN);
			} else if (code == Keyboard.RIGHT) {
				snake.turn(SnakeSegment.RIGHT);
			}
		
		}
		
		private function test(params:Object):void{
			var d:SnakeSegment = params.f;
		}
	}
}